<template>
	<view>
		<!-- <button @click="getBranch">按我</button> -->
		<!-- <a>{{commitData}}</a> -->

		<!-- Form 表单 -->
		<uni-forms ref="form" :modelValue="baseFormData" label-width="80px" border label-align="right">
			<uni-forms-item label="選擇環境" required>
				<uni-data-checkbox multiple v-model="commitData.env_list" :localdata="formData.env"
					@change="change_checkbox" mode="tag" />
			</uni-forms-item>

			<!-- <uni-forms-item label="立即更新" required>
				<uni-data-checkbox v-model="multijobData.UPDATE" :localdata="formData.update" mode="tag" />
			</uni-forms-item> -->

			<uni-forms-item label="選擇分組" required>
				<uni-data-select v-model="filterDataFlag" :localdata="formData.flag"
					@change="change_select"></uni-data-select>
			</uni-forms-item>

			<uni-forms-item label="輸入分支" required>
				<uni-easyinput v-model="commitData.branch_name" placeholder="请输入分支號"></uni-easyinput>
			</uni-forms-item>

		</uni-forms>


		<!-- 以下是列表 -->
		<view class="uni-container">
			<uni-table ref="tableRef" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<!-- <uni-th width="100%" align="center">ID</uni-th> -->
					<uni-th :sortable="true" @sort-change="sortChangeName" width="260px" align="center">項目名称</uni-th>
					<!-- <uni-th width="210px" align="center" :sortable="true" @sort-change="sortChange">分支</uni-th> -->
					<!-- <uni-th width="200px" align="center" :sortable="true">分支</uni-th> -->
				</uni-tr>
				<uni-tr v-for="(item, index) in sortedTableData" :key="index">
					<!-- <uni-td>{{ item.date }}</uni-td> -->
					<uni-td>
						<view class="name">{{ item.server_name }}</view>
					</uni-td>
					<!-- <uni-td>
						<view class="name">{{ item.branch_name }}</view>
					</uni-td> -->
				</uni-tr>
			</uni-table>
			<!-- <view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent"
					:total="total" @change="change" /></view> -->
		</view>

		<button class="button" @click="changeBranch"
			:disabled="this.commitData.b_info.length === 0 || this.commitData.env_list.length === 0 || this.commitData.branch_name.length === 0">修改分支</button>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				apiUrl: "",
				goApiUrl: "",
				getParams: {
					env: "dev-r",
					flag: "backend",
					page_size: 10,
					page: 1
				},
				// api 接口請求回來的數據
				resData: [],
				// 過濾后顯示在表格的數據
				filterData: [],

				// 列表多選時的索引
				selectedIndexs: [],

				// 基础表单数据
				baseFormData: {
					env: 'test-r',
					// update: 'no',
					// branch: '',
				},
				// 数据源
				formData: {
					env: [{
						text: 'dev-r',
						value: 'dev-r'
					}, {
						text: 'test-r',
						value: 'test-r'
					}, {
						text: 'dev-s',
						value: 'dev-s'
					}, {
						text: 'test-s',
						value: 'test-s'
					}],
					flag: [{
						"value": "backend",
						"text": "後端",
						// "disable": true
					}, {
						"value": "frontend",
						"text": "前端"
					}],
				},

				// 過濾數據的標誌(前端或者後端)
				filterDataFlag: "backend",

				commitData: {
					"branch_name": "",
					"env_list": [],
					"b_info": [],
				},

				// 排序字段和顺序
				sortKey: '', // 当前排序字段
				sortOrder: '', // asc | desc
				// 存储排序后的数据（可用于模板和其他方法）
				sortedTableData: [],
			}
		},
		watch: {
			// 监听排序字段或顺序变化
			sortKey: {
				handler() {
					this.applySorting();
				}
			},
			sortOrder: {
				handler() {
					this.applySorting();
					this.clearSelected();
				}
			},
			// tableData 有變化時也重新排序刷新數據，不然不會自動刷新
			filterData: {
				handler() {
					this.applySorting();
					this.clearSelected();
				}
			}
		},
		created() {
			this.sortedTableData = [...this.filterData] // 初始化为原始数据
		},
		methods: {
			getServerName() {
				uni.request({
					url: this.apiUrl + '/apis/branch/servername/',
					method: 'GET',
					// data: this.getParams,
					// sslVerify: false,
					success: (res) => {
						console.log("get 数据：", res.data)
						this.resData = res.data
						this.filterDataHandler()
					},
					fail: (res) => {
						console.log(res.errMsg)
					},
					complete: (res) => {
						console.log('complete')
					}
				})
			},
			// 過濾數據
			filterDataHandler() {
				// 先清空列表
				this.filterData = []
				for (var index = 0; index < this.resData.length; index++) {
					var element = this.resData[index];
					if (element.group === this.filterDataFlag) {
						// console.log("element: ", element)
						this.filterData.push(element)
					}
				}
				this.sortChangeName({
					order: 'ascending'
				})
			},

			// checkbox 分页触发
			change_checkbox(e) {
				console.log("點擊標籤：", e)
				this.commitData.env_list = e.detail.value

			},
			// 分支下拉框 change 事件
			change_select(e) {
				// console.log("change_select:", e)
				this.filterDataFlag = e
				this.filterDataHandler()

			},

			// 执行排序逻辑，并更新 data 中的 sortedTableData
			applySorting() {
				const {
					sortKey,
					sortOrder,
					filterData
				} = this

				if (!sortKey || !sortOrder) {
					// 如果没有排序条件，恢复为原始数据
					this.sortedTableData = filterData.slice()
					return
				}

				// 执行排序
				const sorted = filterData.slice().sort((a, b) => {
					const valA = a[sortKey]
					const valB = b[sortKey]
					let res = 0
					if (valA < valB) res = -1
					else if (valA > valB) res = 1
					else res = 0

					return sortOrder === 'asc' ? res : -res
				})

				// 赋值给 data 变量，可在模板和其他地方使用
				this.sortedTableData = sorted
			},
			// 清除選擇框
			clearSelected() {
				this.$refs.tableRef.clearSelection()
			},

			// 排序時觸發事件 server_name 字段
			sortChangeName(e) {
				console.log("sortChange:", e)
				const {
					order
				} = e
				this.sortKey = 'server_name'
				this.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''

				console.log('排序字段:', this.sortKey, '排序顺序:', this.sortOrder)

				// 触发数据重新计算（computed 会自动响应）
			},

			// 多选
			selectionChange(e) {
				// console.log(e.detail.index)
				console.log("selectionChange: ", e)
				console.log("tableRef: ", this.$refs.tableRef)
				this.selectedIndexs = e.detail.index
				this.selectionData()
			},
			// 多選后的實際數據
			selectionData() {
				// 先清空數組
				this.commitData.b_info = []
				for (const item of this.selectedIndexs) {
					this.commitData.b_info.push(this.sortedTableData[item]);
					// console.log("selectedIndexs: ", this.resData.results[item]);
				}
				// this.multijobData.BRANCH = this.baseFormData.branch
				// this.multijobData.UPDATE = this.baseFormData.update
				console.log("最終提交數據：", this.commitData)
			},

			// 提交更改分支
			changeBranch() {
				uni.request({
					url: this.apiUrl + '/apis/jenkins/bupdateorcreateWelet/',
					method: 'POST',
					data: this.commitData,
					// sslVerify: false,
					success: (res) => {
						console.log("提交更改分支結果: ", res.data)
						this.messageToggle(res, res.data.message)
					},
					fail: (res) => {
						console.log("fail: ", res.errMsg)
						this.messageToggle(res.data.type, res.data.message)
					},
					complete: (res) => {
						console.log('complete')
						// this.filterDataFlag = "backend"
						this.commitData.env_list = []
						this.commitData.branch_name = ""
						this.clearSelected()
					}
				})
			},
			// 消息彈出
			messageToggle(res) {
				uni.showToast({
					title: res.data.message,
					icon: res.data.type === 'success' ? 'success' : 'error',
					duration: 5000,
					mask: false
				})
			}
		},
		mounted() {
			// #ifdef MP-WEIXIN
			this.apiUrl = import.meta.env.VITE_PYTHON_APIURL_WX
			this.goApiUrl = import.meta.env.VITE_GO_APIURL_WX
			// #endif
			// #ifdef WEB
			this.apiUrl = import.meta.env.VITE_PYTHON_APIURL
			this.goApiUrl = import.meta.env.VITE_GO_APIURL
			// #endif

			this.getServerName()

		}

	}
</script>

<style>

</style>